#!/bin/sh

ERL='/usr/local/bin/erl'

SMP=""
DAEMON=""
KPOLL=""
CONF=""
SBIN=""
SNAME=""
COOKIE=""

start()
{
    set -x
    exec $ERL $SMP $DAEMON $KPOLL $SBIN $CONF $SNAME $COOKIE -run xbt
    set +x

    RETVAL=$?
}

stop()
{
    set -x
    exec $ERL -noshell $SMP $KPOLL $SBIN $CONF $SNAME $COOKIE -run xbt_ctl stop
    set +x

    RETVAL=$?
}

usage()
{
    echo "usage: xbt.sh [opts] <start|stop>"
    echo "avaiable options:"
    echo "     -smp Num            -- open SMP mode,and set CPU nums"
    echo "     -daemon             -- run in background"
    echo "     -kpoll              -- use kernel poll"
    echo "     -conf configfile    -- set config file"
    echo "     -pa PATH ...        -- set bean code path"
    echo "     -sname nodename     -- set short node name"
    echo "     -setcookie cookie   -- set cookie"
    echo ""

    exit 1
}

while [ $# -gt 0 ]
do
    arg=$1
    shift;
    case $arg in
        -smp)
            SMP="-smp +S $1";
            shift;;
        -daemon)
            DAEMON="-detached";;
        -kpoll)
            KPOLL="+Ktrue";;
        -conf)
            CONF="-xbt config \"$1\"";
            shift;;
        -pa)
            SBIN="${SBIN} -pa $1";
            shift;;
        -sname)
            SNAME="-sname $1";
            shift;;
        -setcookie)
            COOKIE="-setcookie $1";
            shift;;
        start)
            start;
            ;;
        stop)
            stop
            ;;
        restart)
            stop;
            start;
            ;;
        *)
            usage
    esac
done
if [ -z "$RETVAL" ]; then
    usage
else
    exit $RETVAL
fi
